package com.dries.portal.module.coupon.controller;

import cn.hutool.json.JSONUtil;
import com.dries.common.api.CommonResult;
import com.dries.common.exception.ApiException;
import com.dries.portal.module.coupon.enums.CouponStatus;
import com.dries.portal.module.coupon.entity.Coupon;
import com.dries.portal.module.coupon.form.AcquireTemplateForm;
import com.dries.portal.module.coupon.service.ICouponService;
import com.dries.portal.module.coupon.vo.CouponTemplateSDK;
import com.dries.portal.module.coupon.vo.CouponVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 用户优惠券表
 *
 * @author dries
 * @email samphsanie@gmail.com
 * @date 2020-07-27 13:05:31
 */
@Slf4j
@RestController
@RequestMapping("/coupon")
public class CouponController {

    @Resource
    private ICouponService couponService;

    /**
     * 用户优惠券列表
     */
    @ApiOperation("用户可用优惠券列表")
    @GetMapping("/list/{userId}")
    public CommonResult list(@PathVariable Long userId){

        List<CouponVo> list = couponService.findCouponsByStatus(userId, CouponStatus.USABLE.getCode());
        log.info("用户可用优惠券数量：{}", list.size());
        return CommonResult.success(list);
    }

    /**
     * 用户优惠券详细信息
     */
    @ApiOperation("用户领取的优惠券详细信息")
    @GetMapping("/info/{id}")
    public CommonResult info(@PathVariable("id") Integer id){
		Coupon coupon = couponService.getById(id);
        return CommonResult.success(coupon);
    }

    /**
     * 用户领取优惠券
     */
    @ApiOperation("用户领取优惠券")
    @PostMapping("/getcoupon")
    public CommonResult getCoupon(@RequestBody AcquireTemplateForm form){

        CouponVo couponVo = couponService.acquireTemplate(form);
        if (!Objects.equals(couponVo.getStatus(), CouponStatus.USABLE.getCode())) {
            throw new ApiException("优惠券领取失败");
        }
        log.info("成功领取优惠券=========》{}", JSONUtil.toJsonStr(couponVo));

        return CommonResult.success("成功领取优惠券");
    }

    /**
     * 根据用户ID查找当前可以领取的优惠券模板
     */
    @ApiOperation("查找当前可以领取的优惠券模板")
    @GetMapping("/findcoupon/{userId}")
    public CommonResult findAvailableCouponTemplate(@PathVariable Long userId){

        List<CouponTemplateSDK> sdks = couponService.findAvailableCouponTemplate(userId);

        return CommonResult.success(sdks);
    }


}
